#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "InetAddr.hpp"

enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
    ACCEPT_ERR,
    LISTEN_ERR
};

const static int gbacklog = 8;

using command_service_t = std::function<void(int, InetAddr)>;

class TcpServer
{
public:
    TcpServer(command_service_t service, int port)
        : _port(port),_service(service)
    {
    }

    void Init()
    {
        // socket
        _listensocket = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensocket < 0)
        {
            perror("socket");
            exit(SOCKET_ERR);
        }
        // bind
        sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = INADDR_ANY;

        socklen_t len = sizeof(server);
        if (::bind(_listensocket, (struct sockaddr *)&server, len) < 0)
        {
            perror("bind");
            exit(BIND_ERR);
        }

        // listen
        int n = ::listen(_listensocket, gbacklog);
        if (n < 0)
        {
            perror("listen");
            exit(LISTEN_ERR);
        }
    }

    class ThreadData
    {
    public:
        int _sockfd;
        TcpServer *_self;
        InetAddr _addr;
    public:
        ThreadData(int sockfd, TcpServer *self, InetAddr addr)
            : _sockfd(sockfd), _self(self), _addr(addr)
        {
        }
    };

    void Loop()
    {
        // signal(SIGCHLD, SIG_IGN);
        bool _isrunning = true;
        while (_isrunning)
        {

            // accept
            sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = ::accept(_listensocket, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                std::cout << "accept error" << std::endl;
                continue;
            }
            // service
            InetAddr addr(client);
            std::cout << "client" << "[" << addr.Port() << "]:" << addr.IP() << std::endl;
            pthread_t tid;
            ThreadData *td = new ThreadData(sockfd, this, addr);
            pthread_create(&tid, nullptr, Excute, td); // 1.成员函数默认有this指针
        }
    }

    static void *Excute(void *args)
    {
        pthread_detach(pthread_self()); // 为了让主线程不等待
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_self->_service(td->_sockfd, td->_addr);
        ::close(td->_sockfd);
        delete td;
        return nullptr;
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensocket;

    command_service_t _service;
};